package com.allen.app.common.utils;

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import cn.hutool.core.util.StrUtil;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;

/**
 * Description: 启动工具
 *
 * @author Limiaojun
 * @date 2019/10/6 14:44
 **/
@Slf4j
public class StartUtils {

    /**
     * 打印吉祥马.
     *
     * @param ctx ConfigurableApplicationContext
     * @author Limiaojun
     * @date 2019/10/6 14:15
     */
    public static void printLuckyHorse(ConfigurableApplicationContext ctx,String uri) {
        uri = CheckObjectUtils.isNull(uri) ? "/swagger-ui.html" : uri;
        String host = "localhost";
        uri = uri.startsWith("/") ? uri : "/" + uri;

        try {
            host = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException ignored) {
        }
        Environment bean = ctx.getBean(Environment.class);
        String port = bean.getProperty("server.port");
        String applicationName = bean.getProperty("spring.application.name");

        String rootPath = "http://".concat(host).concat(StrUtil.isBlank(port) ? "" : ":".concat(port));

        //如果没有注册到eurake则不加载mq配置
        if (Objects.equals(Boolean.FALSE.toString(), ctx.getEnvironment().getProperty("eureka.client.enabled"))) {
            HttpHelper.post(rootPath.concat("/root/shut-down/component"),
                Maps.of("pass", ".0.0.0", "endpointType", "SERVICE_OFF"))
            ;
        }

        applicationName = StrUtil.isBlank(applicationName) ? "application" : applicationName;

        /*
          出现这个吉祥马就是程序启动成功的标识， 勿删 ！！
         */
        log.info("\n" + applicationName + " startup success !\n" +
            "                           _(\\_/) \n" +
            "                         ,((((^`\\\n" +
            "                        ((((  (6 \\ \n" +
            "                      ,((((( ,    \\\n" +
            "  ,,,_              ,(((((  /\"._  ,`,\n" +
            " ((((\\\\ ,...       ,((((   /    `-.-'\n" +
            " )))  ;'    `\"'\"'\"\"((((   (      \n" +
            "(((  /            (((      \\\n" +
            " )) |     start-success    |\n" +
            "((  |        .       '     |\n" +
            "))  \\     _ '      `t   ,.')\n" +
            "(   |   y;- -,-\"\"'\"-.\\   \\/  \n" +
            ")   / ./  ) /         `\\  \\\n" +
            "   |./   ( (           / /'\n" +
            "   ||     \\\\          //'|\n" +
            "   ||      \\\\       _//'||\n" +
            "   ||       ))     |_/  ||\n" +
            "   \\_\\     |_/          ||\n" +
            "   `'\"                  \\_\\\n" +
            "                        `'\"\n" + rootPath.concat(uri));

    }

    /**
     * 方法描述:打开浏览器
     *
     * @param url 打开的url
     * @author leon 2016年10月28日 下午4:37:35
     */
    public static void poenBrowser(String url) throws Exception {
        // 获取操作系统的名字
        String osName = System.getProperty("os.name", "");
        if (osName.startsWith("Mac OS")) {
            // 苹果的打开方式
            Class<?> fileMgr = Class.forName("com.apple.eio.FileManager");
            Method openURL = fileMgr.getDeclaredMethod("openURL", String.class);
            openURL.invoke(null, url);
        } else if (osName.startsWith("Windows")) {
            // windows的打开方式。
            Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
        } else {
            // Unix or Linux的打开方式
            String[] browsers = {"firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape"};
            String browser = null;
            for (int count = 0; count < browsers.length && browser == null; count++) {
                // 执行代码，在brower有值后跳出，
                // 这里是如果进程创建成功了，==0是表示正常结束。
                if (Runtime.getRuntime().exec(new String[]{"which", browsers[count]}).waitFor() == 0) {
                    browser = browsers[count];
                }
                if (browser == null) {
                    throw new Exception("Could not find web browser");
                } else {
                    // 这个值在上面已经成功的得到了一个进程。
                    Runtime.getRuntime().exec(new String[]{browser, url});
                }
            }
        }
    }

    public static void printLuckyHorse(ConfigurableApplicationContext ctx) {
        printLuckyHorse(ctx,null);
    }

    /**
     * 判断是linux系统还是其他系统 如果是Linux系统，返回true，否则返回false
     */
    public static boolean isLinux() {
        return System.getProperty("os.name").toLowerCase().contains("linux");
    }
    /**
     * 判断是windows系统还是其他系统 如果是Linux系统，返回true，否则返回false
     */
    public static boolean isWindows() {
        return System.getProperty("os.name").toLowerCase().contains("windows");
    }

    /**
     * 区分系统获取临时目录.
     *
     * @return java.lang.String
     * @author Limiaojun
     * @date 2020/3/14 0014 09:08
     */ 
    public static String getTmpPath(){
        if(isLinux()){
            return "/tmp";
        }else if(isWindows()){
            return "c:/tmp";
        }
        return "";
    }

    public static void setLogLevel(ch.qos.logback.classic.Level level){
        //设置默认日志为info级别,屏蔽httpclient-debug日志 ch.qos.logback.classic.LoggerContext
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        List<Logger> loggerList = loggerContext.getLoggerList();
        loggerList.forEach(logger -> {
            logger.setLevel(level);
        });
    }
}